package com.self.net;

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.SocketAddress;
import java.nio.channels.SocketChannel;

public class UdpServer {

    private int port;

    public UdpServer(int port) {
        this.port = port;
    }

    public void start() {

        try {

            DatagramSocket server = new DatagramSocket(this.port);

            if(!server.isBound()) {
                server.bind(new InetSocketAddress(this.port));
            }

            byte[] buf = new byte[1024*1024];
            DatagramPacket recvPacket = new DatagramPacket(buf,0,buf.length,new InetSocketAddress(this.port));

            while (true) {

                // recv
                server.receive(recvPacket);
                InetAddress inetAddress = recvPacket.getAddress();
                System.out.println(String.format("%s,%s",inetAddress.getHostAddress(),recvPacket.getPort()));

                byte[] data = recvPacket.getData();
                System.out.println(String.format("【Receive】客户端地址[%s] >>>> %s",recvPacket.getAddress().getHostAddress()+":"+recvPacket.getPort(),new String(data,0,recvPacket.getLength(),"utf-8")));



                // send
                String relay = "【Relay】你好,"+(recvPacket.getAddress().getHostAddress()+":"+recvPacket.getPort());
                byte[] sendD = relay.getBytes();
                DatagramPacket send = new DatagramPacket(sendD,sendD.length,inetAddress,recvPacket.getPort());
                server.send(send);

                System.out.println(relay);
            }


        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
